//项目准备
//1.首先下载需要的模块
//expres   express-session  cors  mysql
//2.引入第三方模块
const express = require('express');
const session = require('express-session');
const cors = require('cors');
const mysql = require('mysql');
//3.创建连接池
const pool = mysql.createPool({
  host: '127.0.0.1',
  user: 'root',
  passworld: '',
  port: 3306,
  connectionLimit: 20,
  database: "xz"
})
const poolguys = mysql.createPool({
  host: '127.0.0.1',
  user: 'root',
  passworld: '',
  port: 3306,
  connectionLimit: 20,
  database: "guys"
})
const pooladmin = mysql.createPool({
  host: '127.0.0.1',
  user: 'root',
  passworld: '',
  port: 3306,
  connectionLimit: 20,
  database: "admin"
})
//4.创建服务
const server = express();
server.listen(3000) //监听端口
//5.配置跨域
server.use(cors({
  //5.1配置允许使用的地址
  origin: ['http://127.0.0.1:8080', 'http://localhost:8080'],
  //5.2每请求是否验证 TRUE
  credentials: true
}))
// 7 配置session 在所有请求之前
server.use(session({
  secret: '128位字符串', //安全字符串 进行加密
  resave: true, //一定要正确  每次请求是否更新原有数据
  saveUninitialized: true //保存原始数据
}))
// 7.1 创建session 并保存数据
//req.session.uid = 1;
//7.2获取session中的数据局
//let uid = req.session.uid


//8 配置静态目录
server.use(express.static('public'))

//6.功能一  完成用户登录
server.get('/login', (req, res) => {
  //6.1接收用户名密码
  let u = req.query.uname;
  let p = req.query.upwd;
  //6.2创建sql
  let sql = 'SELECT id,userImg,name FROM xz_login';
  sql += ' WHERE uname = ? AND upwd = md5(?)';
  //6.3执行sql
  pool.query(sql, [u, p], (err, result) => {
    //6.4判断有没有出错
    if (err) throw err;
    //6.5将结果返回
    if (result.length == 0) {
      res.send({
        code: -1,
        msg: '用户名密码错误'
      })
    } else {
      //7.1 获取当前用户的ID
      //result现在是result[{id:?},...]
      let id = result[0].id;
      console.log(result)
      //7.2 将用户ID存在session中
      req.session.uid = id;
      console.log(req.session)
      res.send({
        code: 1,
        msg: '登陆成功',
        uid: req.session.uid,
        userImg: result[0].userImg,
        name: result[0].name,
      })
    }
  })
})
// 功能二  商品分页显示
server.get('/product', (req, res) => {
  // 1.接收客户请求
  let pno = req.query.pno
  let ps = req.query.pagesize
  // 2.接收客户页码请求
  //   pno 页码 pagesize 页大小
  // 3.如果客户没有要求 使用默认值
  //   pno = 1  pagesize = 4
  if (!pno) {
    pno = 1
  }
  if (!ps) {
    ps = 4
  }
  // 4创建sql语句
  let sql = 'SELECT nid,name,img,sole,prices FROM myshop LIMIT ?,?;'
  let offset = (pno - 1) * ps //第一个问号  初始函数
  ps = parseInt(ps)
  // 5执行sql语句
  poolguys.query(sql, [offset, ps], (err, result) => {
    // 6将查询数据返回给客户端
    if (err) throw err
    res.send({
      code: 1,
      msg: '查询成功',
      data: result
    })
  });
})
server.get('/classification', (req, res) => {
  let kindName = req.query.kindName
  let sql = 'SELECT sole,kind,kindName,nid,name,img,sole,prices FROM myshop WHERE kindName=?'
  poolguys.query(sql, kindName, (err, result) => {
    if (err) throw err
    res.send({
      code: 1,
      msg: 'success',
      data: result
    })
  })
})
// 功能三 添加至购物车
server.get('/addcar', (req, res) => {
  //判断用户是否登陆过
  let uid = parseInt(req.query.uid)
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  }
  let lid = req.query.lid
  let price = req.query.price
  let count = req.query.count
  let lname = req.query.lname
  let limg = req.query.limg
  let n = req.query.n
  //先查询顾客是否购买过该商品
  let sql = 'SELECT id FROM car WHERE uid=? AND lid=?'
  poolguys.query(sql, [uid, lid], (err, result) => {
    if (err) throw err;
    if (result.length == 0) {
      //如果顾客一次购买该商品
      var sql = `INSERT INTO car VALUE(null,${lid},${price},${n},'${lname}',${uid},'${limg}')`;

    } else {
      //如果顾客已经购买过一次
      var sql = `UPDATE car SET count=count+${n} WHERE uid=${uid} AND lid=${lid}`;
    }
    poolguys.query(sql, (err, result) => {
      if (err) throw err;
      if (result.affectedRows > 0) {
        res.send({
          code: 1,
          msg: '添加成功'
        })
      } else {
        res.send({
          code: -2,
          msg: '添加失败'
        })
      }
    })
  })
})
//功能四:查看购物车
server.get('/car', (req, res) => {
  //判断用户是否登陆过
  let uid = parseInt(req.query.uid)
  let lid = req.query.lid
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  }
  //通过uid来去数据库里查找用户之前添加过的商品
  //创建sql语句
  let sql = `SELECT id,lid,price,count,lname,limg FROM car WHERE uid=?`
  poolguys.query(sql, uid, (err, result) => {
    if (err) throw err;
    if (result.length > 0) {
      console.log(result)
      res.send({
        data: result,
        code: 1,
        msg: '获取成功'
      })
    } else {
      res.send({
        code: -1,
        msg: '获取失败'
      })
    }
  })

})
//功能:查看库存
server.get('/inventory', (req, res) => {
  //判断用户是否登陆过
  let uid = req.query.uid
  let kindName = req.query.kindName
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  }
  //通过uid来去数据库里查找用户之前添加过的商品
  //创建sql语句
  if (kindName == undefined) {
    let sql = `SELECT soleNum,sole,lid,prices,count,name,img,kind,kindName FROM inventory WHERE uid=?`
    pooladmin.query(sql, uid, (err, result) => {
      if (err) throw err;
      if (result.length > 0) {
        res.send({
          result,
          code: 1,
          msg: '获取成功'
        })
      } else {
        res.send({
          code: -1,
          msg: '获取失败'
        })
      }
    })
  } else {
    let sql = `SELECT sole,lid,prices,count,name,img,kind,kindName FROM inventory WHERE uid=? AND kindName=?`
    pooladmin.query(sql, [uid, kindName], (err, result) => {
      if (err) throw err;
      if (result.length > 0) {
        res.send({
          result,
          code: 1,
          msg: '获取成功'
        })
      } else {
        res.send({
          code: -1,
          msg: '获取失败'
        })
      }
    })
  }


})
// 库存在售数量
server.get('/updataInventory', (req, res) => {
  let uid = req.query.uid
  let lid = req.query.lid
  let soleNum = req.query.soleNum
  let n = req.query.n
  let sql = `UPDATE inventory SET soleNum=soleNum+${n} WHERE uid=${uid} AND lid=${lid}`
  pooladmin.query(sql, (err, result) => {
    if (err) throw err;
    if (result.length > 0) {
      res.send({
        code: 1,
        msg: '操作成功'
      })
    } else {
      res.send({
        code: -2,
        msg: '操作失败'
      })
    }
  })
})
//上架商品
server.get('/putaway', (req, res) => {
  let uid = req.query.uid
  console.log(req.query)
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  }
  let lid = parseInt(req.query.lid)
  let prices = req.query.prices
  let count = req.query.count
  let name = req.query.name
  let img = req.query.img
  let sole = req.query.sole
  let kind = req.query.kind
  let kindName = req.query.kindName
  let n = req.query.n
  //先查询顾客是否上架过该商品
  let sql = 'SELECT id FROM soleing WHERE uid=? AND lid=?'
  pooladmin.query(sql, [uid, lid], (err, result) => {
    console.log(uid, lid)
    if (err) throw err;
    if (result.length == 0) {
      //如果顾客一次上架该商品
      var sql =
        `INSERT INTO soleing VALUE(null,${lid},${uid},'${name}','${img}',${prices},${sole},${n},'${kind}','${kindName}')`;
    } else {
      //如果顾客已经上架过一次
      var sql = `UPDATE soleing SET count=count+${n} WHERE uid=${uid} AND lid=${lid}`;
    }
    pooladmin.query(sql, (err, result) => {
      if (err) throw err;
      if (result.affectedRows > 0) {
        res.send({
          code: 1,
          msg: '操作成功'
        })
      } else {
        res.send({
          code: -2,
          msg: '操作失败'
        })
      }
    })
  })
})
//删除在售列表中的数据
server.get('/delSole', (req, res) => {
  // let uid = req.session.uid
  let uid = req.query.uid
  let lid = req.query.lid
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  }
  //创建删除sql语句
  let sql = `DELETE FROM soleing WHERE lid=? and uid=?`
  pooladmin.query(sql, [lid, uid], (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        code: 1,
        msg: '删除成功'
      })
    } else {
      res.send({
        code: -2,
        msg: '删除失败'
      })
    }
  })
})

//查看在售库存
server.get('/soleing', (req, res) => {
  //判断用户是否登陆过
  let uid = req.query.uid
  let kindName = req.query.kindName
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  }
  //通过uid来去数据库里查找用户之前添加过的商品
  //创建sql语句
  if (kindName == undefined) {
    let sql = `SELECT sole,lid,prices,count,name,img,kind,kindName FROM soleing WHERE uid=?`
    pooladmin.query(sql, uid, (err, result) => {
      if (err) throw err;
      if (result.length > 0) {
        res.send({
          result,
          code: 1,
          msg: '获取成功'
        })
      } else {
        res.send({
          code: -1,
          msg: '获取失败'
        })
      }
    })
  } else {
    let sql = `SELECT sole,lid,prices,count,name,img,kind,kindName FROM soleing WHERE uid=? AND kindName=?`
    pooladmin.query(sql, [uid, kindName], (err, result) => {
      if (err) throw err;
      if (result.length > 0) {
        res.send({
          result,
          code: 1,
          msg: '获取成功'
        })
      } else {
        res.send({
          code: -1,
          msg: '获取失败'
        })
      }
    })
  }
})
//关闭购物车时 发送axios
server.get('/update', (req, res) => {
  let uid = req.session.uid
  let lid = req.query.lid
  let count = req.query.count
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  } //查询购物车内商品的id，并且把count覆盖
  let sqlcount = `UPDATE car SET count=? WHERE uid=? AND lid=?`
  poolguys.query(sqlcount, [count, uid, lid], (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        code: 1,
        msg: '添加成功'
      })
    } else {
      res.send({
        code: -2,
        msg: '添加失败'
      })
    }
  })
})
//删除购物车内的商品
server.get('/delete', (req, res) => {
  // let uid = req.session.uid
  let uid = req.query.uid
  let lid = req.query.lid
  if (!uid) {
    res.send({
      code: -1,
      msg: '请先登录'
    })
    return
  }
  //创建删除sql语句
  let sql = `DELETE FROM car WHERE lid=? and uid=?`
  poolguys.query(sql, [lid, uid], (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        code: 1,
        msg: '删除成功'
      })
    } else {
      res.send({
        code: -2,
        msg: '删除失败'
      })
    }
  })
})
